// testing the ms feature
const test = require('ava')
const { join } = require('path')
const fsx = require('fs-extra')
const debug = require('debug')('jsonql-koa:test:node-client')
const nodeClient = require('jsonql-node-client')
const serverIoCore = require('server-io-core')
// setup
const jsonqlKoa = require('../')
const hello = require('./helpers/hello')
const baseDir = join(__dirname, 'fixtures')
const clientContractDir = join(__dirname, 'fixtures', 'tmp', 'client6002')
const createServer = require('./helpers/server')

const port = 6002;
const dir = 'server6002';
const msPort = 8001;
const startSubServer = require('./helpers/sub-server')

// base test setup
test.before(async t => {

  t.context.baseApp = createServer({
    name: `server${port}`,
    clientConfig: [{
      hostname: `http://localhost:${msPort}`,
      name: 'client0'
    }]
  }, dir)
  t.context.baseServer = t.context.baseApp.listen(port)

  const { app, stop } = startSubServer(msPort)

  t.context.app = app
  t.context.stop = stop
})

test.after(t => {
  t.context.stop()
  t.context.baseServer.close()
  fsx.removeSync(clientContractDir)
  fsx.removeSync(join(baseDir, 'tmp', dir))
})

test.skip(`First test both server is running`, async t => {
  const res1 = await hello(t.context.baseApp)
  t.is(res1.status, 200)
  const res2 = await hello(t.context.app)
  t.is(res2.status, 200)
})

test.skip(`First test calling the 6001 directly with the mutation call`, async t => {
  const client = await nodeClient({
    hostname: `http://localhost:${msPort}`,
    contractDir: join(__dirname, 'fixtures', 'tmp', `client${msPort}`)
  })
  const result = await client.query.subMsService('testing')
  t.truthy(result.indexOf(`ms service`))
})

test(`It should able to call a resolver that access another ms`, async t => {
  // the problem now is calling the 6001 but received the 8001 public contract?
  const client = await nodeClient({
    hostname: `http://localhost:${port}`,
    contractDir: clientContractDir
  })

  const result = await client.mutation.updateMsService('testing')
  t.truthy(result.indexOf(`ms service`))
})
